package com.mxw.commons.exception;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.mxw.commons.errorcode.GlobalErrorCode;
import com.mxw.commons.errorcode.IErrorCode;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode(callSuper = true)
public class CustomException extends RuntimeException {
  private IErrorCode errorCode;

  public String getCodeId() {
    return errorCode.getCodeId();
  }

  public boolean getWhetherDisplay() {
    return errorCode.getWhetherDisplay();
  }

  private CustomException() {}

  public CustomException(String message) {
    this(GlobalErrorCode.SYSTEM_ERROR, message);
  }

  public CustomException(IErrorCode errorCode) {
    this(errorCode, "");
  }

  /** @Description: 优先级：exceptionMsg > errorCodeMsg > errorCodeName */
  public CustomException(IErrorCode errorCode, String message) {
    super(
        CharSequenceUtil.isBlank(message)
            ? CharSequenceUtil.isBlank(errorCode.getMsg())
                ? errorCode.getCodeName()
                : errorCode.getMsg()
            : message);
    this.errorCode = errorCode;
  }

  public String getLogString(String msg) {
    return String.format(
        "%s(%s): %s",
        errorCode.getCodeName(), errorCode.getCodeId(), StrUtil.isBlank(msg) ? this.getMessage() : msg);
  }
}
